package cn.com.ddapp.ddm.util;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.Map;

//跟网络相关的工具类
public class NetUtils {
	public static final String UTF_8 = "UTF-8";

	private final static int RETRY_TIME = 3;

	private NetUtils() {
		/* cannot be instantiated */
		throw new UnsupportedOperationException("cannot be instantiated");
	}

	/**
	 * 判断网络是否连接
	 *
	 * @param context
	 * @return
	 */
	public static boolean isConnected(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (null != connectivity) {
			NetworkInfo info = connectivity.getActiveNetworkInfo();
			if (null != info && info.isConnected()) {
				if (info.getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 判断是否是wifi连接
	 */
	public static boolean isWifi(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm == null)
			return false;
		return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;

	}

	public static boolean isWifi2(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo wifiNetworkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		if(wifiNetworkInfo.isConnected())
		{
			return true ;
		}
		return false ;
	}

    public static String setDecimal(double price) {
        DecimalFormat df = new DecimalFormat("######0.00");
        return df.format(price);
    }

	/**
	 * 打开网络设置界面
	 */
	public static void openSettingForNet(Activity activity) {
		Intent intent = new Intent("/");
		ComponentName cm = new ComponentName("com.android.settings",
				"com.android.settings.WirelessSettings");
		intent.setComponent(cm);
		intent.setAction("android.intent.action.VIEW");
		activity.startActivityForResult(intent, 0);
	}
	private static String appCookie;

//	private static String getCookie(AppContext application) {
//		if (appCookie == null || appCookie == "") {
//			appCookie = application.getProperty(AppConfig.CONF_COOKIE);
//		}
//		return appCookie;
//	}

	private static String appUserAgent;

//	private static String getUserAgent(AppContext application) {
//		if (appUserAgent == null || appUserAgent == "") {
//			StringBuilder ua = new StringBuilder("http://192.168.1.116:8080/english-baby/api");
//			ua.append('/' + application.getPackageInfo().versionName + '_' + application.getPackageInfo().versionCode);// App版本
//			ua.append("/Android");// 手机系统平台
//			ua.append("/" + android.os.Build.VERSION.RELEASE);// 手机系统版本
//			ua.append("/" + android.os.Build.MODEL); // 手机型号
//			ua.append("/" + application.getAppId());// 客户端唯一标识
//			appUserAgent = ua.toString();
//		}
//		return appUserAgent;
//	}
	private final static int TIMEOUT_CONNECTION = 20000;
	private final static int TIMEOUT_SOCKET = 20000;

	private static HttpClient getHttpClient() {
		HttpClient httpClient = new HttpClient();
		// 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
		httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
		// 设置 默认的超时重试处理策略
		httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		// 设置 连接超时时间
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT_CONNECTION);
		// 设置 读数据超时时间
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT_SOCKET);
		// 设置 字符集
		httpClient.getParams().setContentCharset(UTF_8);
		return httpClient;
	}

	private static PostMethod getHttpPost(String url) {

		PostMethod httpPost = new PostMethod(url);
		// 设置 请求超时时间
		httpPost.getParams().setSoTimeout(TIMEOUT_SOCKET);
		httpPost.setRequestHeader("Host", "http://139.224.69.131:8080/");
		httpPost.setRequestHeader("Connection", "Keep-Alive");
//		httpPost.setRequestHeader("Cookie", cookie);
//		httpPost.setRequestHeader("User-Agent", userAgent);
		return httpPost;
	}

	public static String _Nullpost(String url, Map<String, Object> params
	) {
		// System.out.println("post_url==> "+url);
//		String cookie = getCookie(appContext);
//		String userAgent = getUserAgent(appContext);

		HttpClient httpClient = null;
		PostMethod httpPost = null;

		// post表单参数处理
		int length = (params == null ? 0 : params.size()) ;
		Part[] parts = new Part[length];
		int i = 0;
		if (params != null)
			for (String name : params.keySet()) {
				parts[i++] = new StringPart(name, String.valueOf(params.get(name)), UTF_8);
				// System.out.println("post_key==> "+name+"
				// value==>"+String.valueOf(params.get(name)));
			}
		String responseBody = "";
		int time = 0;
		do {
			try {
				httpClient = getHttpClient();
				httpPost = getHttpPost(url);
				httpPost.setRequestEntity(new MultipartRequestEntity(parts, httpPost.getParams()));
				int statusCode = httpClient.executeMethod(httpPost);
				if (statusCode != HttpStatus.SC_OK) {

				} else if (statusCode == HttpStatus.SC_OK) {
					Cookie[] cookies = httpClient.getState().getCookies();
					String tmpcookies = "";
					for (Cookie ck : cookies) {
						tmpcookies += ck.toString() + ";";
					}
					// 保存cookie
					if ( tmpcookies != "") {
//						appContext.setProperty("cookie", tmpcookies);
						appCookie = tmpcookies;
					}
				}
				InputStream responseBodyAsStream = httpPost.getResponseBodyAsStream();
				responseBody = stream2Str(responseBodyAsStream);

				break;
			} catch (IOException e) {
				time++;
				if (time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
					}
					continue;
				}
				// 发生网络异常
				e.printStackTrace();

			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}finally {
				// 释放连接
				httpPost.releaseConnection();
				httpClient = null;
			}
		} while (time < RETRY_TIME);

		responseBody = responseBody.replaceAll("\\p{Cntrl}", "");
		return responseBody;
	}

	public static String stream2Str(InputStream is) throws IOException{
		if(is==null)return null;
		byte[] b = new byte[10240];
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		while(is.read(b)!=-1){
			baos.write(b);
		}
		byte[] bytes = baos.toByteArray();
		return new String(bytes);
	}
}
